<template>
  <div>
    <h3>比赛成绩</h3>
    <div class="table-body">
      <vxe-toolbar style="height: 100px;">
        <template #buttons>
          <el-row style="margin-bottom: 20px;">
            <el-col :span="5" style="display: flex;">
              <el-select v-model="searchForm.matchLevelId" multiple size="small" collapse-tags
                filterable clearable placeholder="选择赛事级别">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_matchLevel" :key="index">
                </el-option>
              </el-select>
              <el-button type="success" size="small" @click="searchForm.matchLevelId = Object.keys(dict_matchLevel)">全选</el-button>
            </el-col>
            <el-col :span="5" style="display: flex;">
              <el-select v-model="searchForm.matchKinId" multiple style="margin-left: 20px;" size="small" collapse-tags
                filterable clearable placeholder="选择赛事类别">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_matchKin" :key="index">
                </el-option>
              </el-select>
              <el-button type="success" size="small" @click="searchForm.matchKinId = Object.keys(dict_matchKin)">全选</el-button>
            </el-col>
            <el-col :span="4" style="display: flex;">
              <el-select v-model="searchForm.matchEventId" @change="searchMatchEventChange" style="margin-left: 20px;" size="small" collapse-tags
                filterable clearable placeholder="选择参赛项目">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_matchEvent" :key="index">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="4" style="display: flex;">
              <el-select v-model="searchForm.matchEventItemId" style="margin-left: 20px;" size="small" collapse-tags
                filterable clearable placeholder="选择参赛小项">
                <el-option :label="item.name" :value="item.matchEventItemId" v-for="(item,index) in matchEventItemData" :key="index">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="4" style="display: flex;">
              <el-select v-model="searchForm.sportId" style="margin-left: 20px;" size="small" collapse-tags
                filterable clearable placeholder="选择运动项目">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_sport" :key="index">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="5" style="display: flex;">
              <el-button type="success" icon="el-icon-plus" size="medium" @click="insertEvent">新增</el-button>
              <el-button type="success" icon="el-icon-printer" size="medium" @click="exportData">导出</el-button>
              <el-button type="success" icon="el-icon-printer" size="medium" @click="printEvent">打印</el-button>
            </el-col>
            <el-col :span="5">
              <el-date-picker size="small" v-model="doubleDate" type="daterange" align="right" unlink-panels style="width: 80%;"
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions">
              </el-date-picker>
            </el-col>
            <el-col :span="4" style="display: flex;">
              <el-select v-model="searchForm.coachId" style="margin-left: 20px;" size="small" collapse-tags
                filterable clearable placeholder="选择教练">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_coach" :key="index">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="3" style="display: flex;">
              <el-input v-model="searchForm.matchRank" type="number" size="small" placeholder="输入名次" style="width: 60%;"></el-input>
            </el-col>
            <el-col :span="4" style="display: flex;">
              <el-button type="success" size="small" icon="el-icon-s-promotion" @click="searchSubmit"
                style="margin: 0 10px;">
                搜索</el-button>
              <vxe-button @click="clearTableFilter" status="warning" icon="el-icon-refresh-right"> 清空</vxe-button>
            </el-col>
            <el-col :span="3">
              <vxe-input style="float: right;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索"
                @input="searchEvent"></vxe-input>
            </el-col>
          </el-row>
        </template>
      </vxe-toolbar>
      <vxe-table resizable ref="XTable" border max-height="800" stripe highlight-hover-row highlight-current-row
        :loading="loading" :data="dataList" @sort-change="sortChange">
        <vxe-table-column field="player" title="运动员" sortable></vxe-table-column>
        <vxe-table-column field="coachNames" title="教练员" sortable></vxe-table-column>
        <vxe-table-column field="sport" title="运动项目" sortable></vxe-table-column>
        <vxe-table-column field="sportItem" title="运动小项" sortable></vxe-table-column>
        <vxe-table-column field="matchDate" title="比赛时间" sortable></vxe-table-column>
        <vxe-table-column field="matchName" title="赛事名称" sortable></vxe-table-column>
        <vxe-table-column field="matchLevel" title="赛事级别" sortable></vxe-table-column>
        <vxe-table-column field="matchKin" title="赛事类别" sortable></vxe-table-column>
        <vxe-table-column field="matchEvent" title="参赛项目" sortable></vxe-table-column>
        <vxe-table-column field="matchEventItem" title="参赛小项" sortable></vxe-table-column>
        <vxe-table-column field="matchGroupType" title="组别" sortable></vxe-table-column>
        <vxe-table-column field="delegation" title="代表队" sortable></vxe-table-column>
        <vxe-table-column field="matchResult" title="成绩" sortable></vxe-table-column>
        <vxe-table-column field="matchRank" title="名次" sortable></vxe-table-column>
        <vxe-table-column field="matchAddress" title="比赛地点" sortable></vxe-table-column>
        <vxe-table-column field="recordBreak" title="破纪录" sortable></vxe-table-column>
        <vxe-table-column field="multiPlayerMatch" title="个人/团体" sortable></vxe-table-column>
        <vxe-table-column field="memo" title="备注" sortable></vxe-table-column>
   <!--     <vxe-table-column field="regPR" title="注册省/市" sortable></vxe-table-column>
        <vxe-table-column field="regCT" title="注册市/区" sortable></vxe-table-column>
        <vxe-table-column field="reg" title="注册县" sortable></vxe-table-column> -->
        <vxe-table-column field="" title="操作" width="150">
          <template #default="{ row,rowIndex }">
              <el-button @click="editEvent(row,rowIndex)" type="success" size="medium" icon="el-icon-edit" circle></el-button>
              <el-button @click="deleteEvent(row)" type="danger" size="medium" icon="el-icon-delete" circle></el-button>
              <el-tooltip class="item" effect="dark" content="复制此条记录为新增模板" placement="top">
                <el-button @click="copyEvent(row)" type="primary" size="medium" icon="el-icon-tickets" circle></el-button>
              </el-tooltip>
          </template>
        </vxe-table-column>
        <vxe-table-column field="createUser" title="录入人" sortable></vxe-table-column>
        <vxe-table-column field="checkUser" title="审核人" sortable>
          <template #default="{ row }">
            <span v-if="row.checkUserId!=0">{{row.checkUser}}</span>
            <el-link v-else @click="checkedEvent(row)" type="success">{{row.checkUser}}</el-link>
          </template>
        </vxe-table-column>
        <vxe-table-column field="fileName" title="文件" sortable  width="150">
          <template #default="{ row }">
            <div v-loading="row.downloadShow">
              <el-upload
                class="upload-demo"
                action="/match/fileUpload"
                :on-change="beforeFileUpload"
                :limit="1"
                :auto-upload="false"
                :show-file-list="false"
                :file-list="fileList">
                <el-button @click="clickFileUpload(row)" size="medium" type="primary">选择文件</el-button>
              </el-upload>
              <div v-show="row.fileName">
                <el-link @click="downloadFile(row)" type="success">下载-{{row.fileName}}</el-link>
              </div>
            </div>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize" :total="page.totalResult"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="handlePageChange">
      </vxe-pager>
    </div>
    <vxe-modal v-model="insertModal" title="比赛成绩" width="600" height="80%">
      <template #default>
        <el-form inline-message ref="insertForm" :rules="rules" :model="insertForm" label-width="100px"  style="padding: 0 50px;">
          <el-form-item label="比赛时间" prop="matchDate">
            <el-date-picker type="date" placeholder="选择日期" v-model="insertForm.matchDate" style="width: 80%;">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="运动项目" prop="sportId">
            <el-select v-model="insertForm.sportId" @change="sportChange" filterable clearable style="width: 80%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_sport" :key="index">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="运动小项" prop="sportItemId">
            <el-select v-model="insertForm.sportItemId" filterable clearable style="width: 80%;"
              placeholder="请选择">
              <el-option :label="item.name" :value="item.sportItemId" v-for="(item,index) in sportItemData" :key="index">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="参赛项目" prop="matchEventId">
            <el-select v-model="insertForm.matchEventId" @change="matchEventChange" filterable clearable style="width: 80%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_matchEvent" :key="index">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="参赛小项" prop="matchEventItemId">
            <el-select v-model="insertForm.matchEventItemId" filterable clearable style="width: 80%;" placeholder="请选择">
              <el-option :label="item.name" :value="item.matchEventItemId" v-for="(item,index) in matchEventItemData" :key="index">
              </el-option>
            </el-select>
            <el-link v-if="!matchEventItemIdShow" @click="matchEventItemIdInsertClick" style="font-size: 80%;" icon="el-icon-plus" type="success">点击新增</el-link>
            <el-input v-else style="margin-top: 10px;" placeholder="请输入参赛小项" v-model="matchEventItemName" class="input-with-select">
              <el-button @click="matchEventItemIdInsert" slot="append" icon="iconfont icon-save"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="教练" prop="coaches">
            <el-select v-model="insertForm.coaches" multiple filterable clearable style="width: 80%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_coach" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="个人/团体" prop="multiPlayerMatch">
            <el-radio v-model="insertForm.multiPlayerMatch" label="个人"></el-radio>
            <el-radio v-model="insertForm.multiPlayerMatch" label="团体"></el-radio>
          </el-form-item>
          <el-form-item label="运动员" prop="playerId">
            <el-select v-model="insertForm.playerId" @change="playerChange" :multiple="isMultiPlayerMatch" filterable clearable style="width: 80%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_player" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="性别" prop="genderId">
            <el-select v-model="insertForm.genderId" disabled filterable clearable style="width: 80%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_gender" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="组别" prop="matchGroupTypeId">
            <el-select v-model="insertForm.matchGroupTypeId" filterable clearable style="width: 80%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_matchGroupType" :key="index"></el-option>
            </el-select>
            <el-link v-if="!matchGroupTypeIdShow" @click="matchGroupTypeIdShow = true" style="font-size: 80%;" icon="el-icon-plus" type="success">点击新增</el-link>
            <el-input v-else style="margin-top: 10px;" placeholder="请输入组别" v-model="matchGroupTypeName" class="input-with-select">
              <el-button @click="matchGroupTypeIdInsert" slot="append" icon="iconfont icon-save"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="赛事名称" prop="matchName">
            <el-input v-model="insertForm.matchName" style="width: 80%;"></el-input>
          </el-form-item>
          <el-form-item label="赛事级别" prop="matchLevelId">
            <el-select v-model="insertForm.matchLevelId" filterable clearable style="width: 80%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_matchLevel" :key="index">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="赛事类别" prop="matchKindId">
            <el-select v-model="insertForm.matchKindId" filterable clearable style="width: 80%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_matchKin" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="名次" prop="matchRank">
            <el-input v-model="insertForm.matchRank" type="number" style="width: 80%;" @input="changeInput" @focus="changeInput"></el-input>
          </el-form-item>
          <el-form-item label="比赛成绩" prop="matchResult">
            <el-input v-model="insertForm.matchResult" style="width: 80%;"></el-input>
          </el-form-item>
          <el-form-item label="破纪录" prop="recordBreakId">
            <el-select v-model="insertForm.recordBreakId" filterable clearable style="width: 80%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_recordBreak" :key="index">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="代表队" prop="delegationId">
            <el-select v-model="insertForm.delegationId" filterable clearable style="width: 80%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_delegation" :key="index"></el-option>
            </el-select>
            <el-link v-if="!delegationIdShow" @click="delegationIdShow = true" style="font-size: 80%;" icon="el-icon-plus" type="success">点击新增</el-link>
            <el-input v-else style="margin-top: 10px;" placeholder="请输入代表队" v-model="delegationName" class="input-with-select">
              <el-button @click="delegationIdInsert" slot="append" icon="iconfont icon-save"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="协议" prop="protocol">
            <el-input v-model="insertForm.protocol" style="width: 80%;"></el-input>
          </el-form-item>
          <el-form-item label="比赛地点" prop="matchAddressId">
            <el-select v-model="insertForm.matchAddressId" filterable clearable style="width: 80%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_matchAddress" :key="index">
              </el-option>
            </el-select>
            <el-link v-if="!matchAddressIdShow" @click="matchAddressIdShow = true" style="font-size: 80%;" icon="el-icon-plus" type="success">点击新增</el-link>
            <el-input v-else style="margin-top: 10px;" placeholder="请输入比赛地点" v-model="matchAddressName" class="input-with-select">
              <el-button @click="matchAddressIdInsert" slot="append" icon="iconfont icon-save"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="备注" prop="memo">
            <el-input v-model="insertForm.memo" style="width: 80%;"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="warning" size="small" @click="insertModal = false">取消</el-button>
            <el-button type="success" size="small" icon="el-icon-s-promotion" @click="insertSave">保存</el-button>
          </el-form-item>
        </el-form>
      </template>
    </vxe-modal>
  </div>
</template>
<script>
  import {
    player_match,
    player_match_insert,
    player_match_update,
    player_match_check,
    player_match_delete,
    player_match_select,
    match_fileUpload,
    match_filePath4pdf,
    sport_item_by_sportId,
    match_event_item_by_matchEventId,
    match_event_item_insert,
    match_group_type_insert,
    delegation_insert,
    match_address_insert,
    fileDownload_match
  } from '@/api/person.js'
  import {
    userId2EmpName,
    coachByOrgIgnoreRole,
    currentRolePlayer,
    sport_by_org,
    sport_item,
    match_event,
    match_event_item,
    getDelegation,
    record_break,
    match_level,
    match_group_type,
    match_kind,
    match_address,
  } from '@/api/dict.js'
  import sportChangesportItem from '@/components/sport2sportItem/sport2sportItem.vue'
  export default {
    components: {
      sportChangesportItem
    },
    data() {
      return {
        doubleDate: '',
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        defaultDataList: [],
        dataList: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        filterName: '',
        insertModal: false,
        dict_gender: {1:'男',2:'女'},
        dict_coach: {},
        dict_sport: {},
        dict_matchLevel: {},
        dict_matchKin: {},
        dict_matchEvent: {},
        dict_matchEventItem: {},
        dict_player: {},
        dict_delegation: {},
        dict_recordBreak: {},
        dict_multiPlayerMatch: {'个人':'个人','团体':'团体'},
        dict_matchAddress: {},
        dict_matchGroupType: {},
        dict_createUser: {},
        dict_checkUser: {},
        dict_userId2empName: {},
        insertForm: {
          coaches: '',
          matchDate: '',
          matchName: '',
          matchLevelId: '',
          sportId: '',
          sportItemId: '',
          matchKindId: '',
          matchEventId: '',
          matchEventItemId: '',
          playerId: '',
          genderId: '',
          matchGroupTypeId: '',
          matchResult: '',
          delegationId: '',
          matchRank: '',
          recordBreakId: '',
          multiPlayerMatch: '团体',
          protocol: '',
          matchAddressId: '',
          memo: '',
        },
        searchForm: {
          coachId: '',
          sportId: '',
          matchLevelId: '',
          matchKinId: '',
          matchEventId: '',
          matchEventItemId: '',
          matchRank: '',
        },
        sportItemData: [],
        matchEventItemData: [],
        rules: {
          matchName: [{
            required: true,
            message: '这是必填项',
            trigger: 'blur'
          }, ],
          matchDate: [{
            required: true,
            message: '这是必填项',
            trigger: 'blur'
          }, ],
          sportId: [{
            required: true,
            message: '这是必填项',
            trigger: 'blur'
          }, ],
          matchEventId: [{
            required: true,
            message: '这是必填项',
            trigger: 'blur'
          }, ],
          matchEventItemId: [{
            required: true,
            message: '这是必填项',
            trigger: 'blur'
          }, ],
          multiPlayerMatch: [{
            required: true,
            message: '这是必填项',
            trigger: 'blur'
          }, ],
          playerId: [{
            required: true,
            message: '这是必填项',
            trigger: 'blur'
          }, ],
        },
        isInsert: true,
        matchId: '',
        pid: '',
        fileList: [],
        fileRow: {},
        matchEventItemIdShow: false,
        matchEventItemName: '',
        matchGroupTypeIdShow: false,
        matchGroupTypeName: '',
        delegationIdShow: false,
        delegationName: '',
        matchAddressIdShow: false,
        matchAddressName: '',
        columns: [],
        dict_playerId_genderId: {},
        search: false,
        currentIndex: null,
        isMultiPlayerMatch: true,
      }
    },
    created() {
      this.init_dict().then(() => {
        this.player_match()
      })
    },
    computed: {
      openDateValid() {
        if (this.insertForm.openDate && this.insertForm.closeDate) {
          if (this.insertForm.openDate > this.insertForm.closeDate) {
            this.$message.error('开始时间必须小于结束时间！')
            return false
          } else {
            return true
          }
        } else {
          return true
        }
      },
    },
    watch: {
      filterName(val) {
        if(!val){
          this.page = {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0,
          }
          this.search = false
          this.findList()
        }
      },
      'insertForm.multiPlayerMatch':{
        deep:true,
        handler:function(newV,oldV){
          this.insertForm.playerId = ''
          this.insertForm.genderId = ''
          if(newV == '团体'){
            this.isMultiPlayerMatch = true
          }else if(newV == '个人'){
            this.isMultiPlayerMatch = false
          }
        }
      }
    },
    methods: {
      copyEvent(row) {
        if (row.coaches) this.insertForm.coaches = row.coaches.split(',')
        if (row.matchDate) this.insertForm.matchDate = this.$moment(row.matchDate).format('YYYY-MM-DD') + ' 00:00:00'
        if (row.matchName) this.insertForm.matchName = row.matchName
        if (row.matchLevelId) this.insertForm.matchLevelId = row.matchLevelId!=0?row.matchLevelId+'':''
        if (row.sportId) this.insertForm.sportId = row.sportId+''
        this.sportChange()
        if (row.sportItemId) this.insertForm.sportItemId = row.sportItemId!=0?row.sportItemId+'':''
        if (row.matchKindId) this.insertForm.matchKindId = row.matchKindId!=0?row.matchKindId+'':''
        if (row.matchEventId) this.insertForm.matchEventId = row.matchEventId+''
        this.matchEventChange()
        if(this.dict_matchEventItem[row.matchEventItemId]){
          if (row.matchEventItemId) this.insertForm.matchEventItemId = row.matchEventItemId+''
        }else{
          if (row.matchEventItemId) this.insertForm.matchEventItemId = ''
        }
        if (row.multiPlayerMatch) this.insertForm.multiPlayerMatch = row.multiPlayerMatch
        if(row.multiPlayerMatch=='团体') {
          if (row.players) {
            this.insertForm.playerId = row.players.split(',')
          }else{
            this.insertForm.playerId = []
          }
        }else{
          if (row.playerId) this.insertForm.playerId = [row.playerId+'']
        }
        if (row.genderId) this.insertForm.genderId = row.genderId+''
        if (row.matchGroupTypeId) this.insertForm.matchGroupTypeId = row.matchGroupTypeId!=0?row.matchGroupTypeId+'':''
        if (row.matchResult) this.insertForm.matchResult = row.matchResult
        if (row.delegationId) this.insertForm.delegationId = row.delegationId!=0?row.delegationId+'':''
        if (row.matchRank) this.insertForm.matchRank = row.matchRank
        if (row.recordBreakId) this.insertForm.recordBreakId = row.recordBreakId!=0?row.recordBreakId+'':''
        if (row.protocol) this.insertForm.protocol = row.protocol
        if (row.matchAddressId) this.insertForm.matchAddressId = row.matchAddressId!=0?row.matchAddressId+'':''
        if (row.memo) this.insertForm.memo = row.memo
        this.isInsert = true
        this.insertModal = true
      },
      changeInput() {
        var pattern = /^[1-9][0-9]*$/ // 正整数的正则表达式
        // 不符合正整数时
        if (!pattern.test(this.insertForm.matchRank)) {
          // input 框绑定的内容为空
          this.insertForm.matchRank = ''
        }
      },
      playerChange(val){
        if(this.dict_playerId_genderId[val]){
          this.insertForm.genderId = this.dict_playerId_genderId[val]+''
        }else{
          this.insertForm.genderId = ''
        }
      },
      matchAddressIdInsert(){
        match_address_insert({name:this.matchAddressName}).then(res=>{
          if(res.code === 200){
            this.$message.success('添加成功！')
            match_address().then(res => {
              this.dict_matchAddress = res
            })
            this.matchAddressIdShow = false
          }else{
            this.$message.error('添加失败！')
            this.matchAddressIdShow = false
          }
        })
      },
      delegationIdInsert(){
        delegation_insert({name:this.delegationName}).then(res=>{
          if(res.code === 200){
            this.$message.success('添加成功！')
            getDelegation().then(res => {
              this.dict_delegation = res
            })
            this.delegationIdShow = false
          }else{
            this.$message.error('添加失败！')
            this.delegationIdShow = false
          }
        })
      },
      matchGroupTypeIdInsert(){
        match_group_type_insert({name:this.matchGroupTypeName}).then(res=>{
          if(res.code === 200){
            this.$message.success('添加成功！')
            match_group_type().then(res => {
              this.dict_matchGroupType = res
            })
            this.matchGroupTypeIdShow = false
          }else{
            this.$message.error('添加失败！')
            this.matchGroupTypeIdShow = false
          }
        })
      },
      matchEventItemIdInsert(){
        match_event_item_insert({name:this.matchEventItemName,matchEventId:this.insertForm.matchEventId}).then(res=>{
          if(res.code === 200){
            this.$message.success('添加成功！')
            this.matchEventChange()
            this.matchEventItemIdShow = false
          }else{
            this.$message.error('添加失败！')
            this.matchEventItemIdShow = false
          }
        })
      },
      matchEventItemIdInsertClick(){
        if(this.insertForm.matchEventId){
          this.matchEventItemIdShow = true
        }else{
          this.$message.warning('请选择所属的参赛项目')
        }
      },
      downloadFile(row){
        row.downloadShow = true
        this.$forceUpdate()
        fileDownload_match(row.matchId).then(res=>{
           try {
              var blob = res.data;
             // FileReader主要用于将文件内容读入内存
              var reader = new FileReader();
              reader.readAsDataURL(blob);
              // onload当读取操作成功完成时调用
              reader.onload = function(e) {
                var a = document.createElement('a');
                // 获取文件名fileName
                var fileName = res.headers["content-disposition"].split("=");
                fileName = fileName[fileName.length - 1];
                fileName = fileName.replace(/"/g, "");
                fileName = decodeURI(fileName)
                a.download = fileName;
                a.href = e.target.result;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
              }
            }catch{
               this.$message.warning('没有找到文件！')
            }
            row.downloadShow = false
            this.$forceUpdate()
        })
      },
      beforeFileUpload(file){
        this.fileRow.downloadShow = true
        if (file.size > 1024 * 1024 * 100) {
          this.fileRow.downloadShow = false
          this.fileRow = {}
          this.fileList = []
          this.$message.error('上传文件太大!不能超过100M');
          return
        }
        let fileName = encodeURI(file.name)
        let fileData = new FormData()
        fileData.append("fileName",this.fileRow.matchId+"-"+ fileName);
        fileData.append("file", file.raw);
        match_fileUpload(fileData).then(res=>{
          if(res.code === 200) {
            this.fileRow.fileName = this.fileRow.matchId+"-"+ file.name
            this.fileRow.downloadShow = false
            this.$message.success('上传成功!')
            this.fileRow = {}
            this.fileList = []
          }else{
            this.$message.error('上传失败!')
            this.fileRow.downloadShow = false
          }
        })
      },
      clickFileUpload(row){
        this.fileRow = row
      },
      clearTableFilter() {
        this.searchForm = {
          coachId: '',
          sportId: '',
          matchLevelId: '',
          matchKinId: '',
          matchEventId: '',
          matchEventItemId: '',
          matchRank: '',
        }
        this.doubleDate = ''
        this.player_match()
      },
      searchSubmit() {
        let data = {}
        if (this.searchForm.coachId) data.coachId = this.searchForm.coachId
        if (this.searchForm.sportId) data.sportId = this.searchForm.sportId
        if (this.searchForm.matchLevelId) data.matchLevelStr = this.searchForm.matchLevelId.join(',')
        if (this.searchForm.matchKinId) data.matchKindStr = this.searchForm.matchKinId.join(',')
        if (this.searchForm.matchEventId) data.matchEventId = this.searchForm.matchEventId
        if (this.searchForm.matchEventItemId) data.matchEventItemId = this.searchForm.matchEventItemId
        if (this.searchForm.matchRank) data.matchRank = this.searchForm.matchRank
        if (this.doubleDate) {
          data.dateStart = this.$moment(this.doubleDate[0]).format('YYYY-MM-DD') + ' 00:00:00'
          data.dateEnd = this.$moment(this.doubleDate[1]).format('YYYY-MM-DD') + ' 00:00:00'
        }
        player_match_select(data).then(res => {
          if (res.code === 200 && res.data.length != 0) {
            this.page = {
              currentPage: 1,
              pageSize: 10,
              totalResult: 0
            }
            this.init_data(res.data)
          } else {
            this.defaultDataList = []
          }
        }).then(() => {
          this.findList()
        })
      },
      deleteEvent(row) {
        this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          player_match_delete({
            matchId: row.matchId
          }).then(res => {
            if (res.code === 200) {
              this.defaultDataList.forEach((item,index)=>{
              	if(item.matchId == row.matchId){
              	  this.defaultDataList.splice(index,1)
              	}
              })
              this.init_data(this.defaultDataList)
              this.findList()
              this.$message.success('删除成功！')
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      checkedEvent(row) {
        this.$confirm('注意：审核过之后，该条数据将不能再被修改', '审核', {
          confirmButtonText: '√通过审核',
          cancelButtonText: '放弃审核',
          type: 'warning'
        }).then(() => {
          player_match_check({
            matchId: row.matchId
          }).then(res => {
            if (res.code === 200) {
              this.player_match()
              this.$message.success('已审核.！')
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消审核.'
          });
        });
      },
      editEvent(row,rowIndex) {
        this.currentIndex = rowIndex
        if (row.checkUserId!=0) {
          this.$message.warning('已经审核过的数据不能修改')
        } else {
          this.matchId = row.matchId
          if (row.coaches) this.insertForm.coaches = row.coaches.split(',')
          if (row.matchDate) this.insertForm.matchDate = this.$moment(row.matchDate).format('YYYY-MM-DD') + ' 00:00:00'
          if (row.matchName) this.insertForm.matchName = row.matchName
          if (row.matchLevelId) this.insertForm.matchLevelId = row.matchLevelId!=0?row.matchLevelId+'':''
          if (row.sportId) this.insertForm.sportId = row.sportId+''
          this.sportChange()
          if (row.sportItemId) this.insertForm.sportItemId = row.sportItemId!=0?row.sportItemId+'':''
          if (row.matchKindId) this.insertForm.matchKindId = row.matchKindId!=0?row.matchKindId+'':''
          if (row.matchEventId) this.insertForm.matchEventId = row.matchEventId+''
          this.matchEventChange()
          if(this.dict_matchEventItem[row.matchEventItemId]){
            if (row.matchEventItemId) this.insertForm.matchEventItemId = row.matchEventItemId+''
          }else{
            if (row.matchEventItemId) this.insertForm.matchEventItemId = ''
          }
          if (row.multiPlayerMatch) this.insertForm.multiPlayerMatch = row.multiPlayerMatch
          if(row.multiPlayerMatch=='团体') {
            if (row.players) {
              this.insertForm.playerId = row.players.split(',')
            }else{
              this.insertForm.playerId = []
            }
          }else{
            if (row.playerId) this.insertForm.playerId = [row.playerId+'']
          }
          if (row.genderId) this.insertForm.genderId = row.genderId+''
          if (row.matchGroupTypeId) this.insertForm.matchGroupTypeId = row.matchGroupTypeId!=0?row.matchGroupTypeId+'':''
          if (row.matchResult) this.insertForm.matchResult = row.matchResult
          if (row.delegationId) this.insertForm.delegationId = row.delegationId!=0?row.delegationId+'':''
          if (row.matchRank) this.insertForm.matchRank = row.matchRank!=0?row.matchRank:''
          if (row.recordBreakId) this.insertForm.recordBreakId = row.recordBreakId!=0?row.recordBreakId+'':''
          if (row.protocol) this.insertForm.protocol = row.protocol
          if (row.matchAddressId) this.insertForm.matchAddressId = row.matchAddressId!=0?row.matchAddressId+'':''
          if (row.memo) this.insertForm.memo = row.memo
          this.isInsert = false
          this.insertModal = true
        }
      },
      insertSave() {
        this.$refs.insertForm.validate((valid) => {
          if (valid && this.openDateValid) {
            let data = {}
            if (this.insertForm.coaches) data.coaches = this.insertForm.coaches.join(',')
            if (this.insertForm.matchDate) data.matchDate = this.$moment(this.insertForm.matchDate).format(
              'YYYY-MM-DD') + ' 00:00:00'
            if (this.insertForm.matchName) data.matchName = this.insertForm.matchName
            if (this.insertForm.matchLevelId) data.matchLevelId = this.insertForm.matchLevelId
            if (this.insertForm.sportId) data.sportId = this.insertForm.sportId
            if (this.insertForm.sportItemId) data.sportItemId = this.insertForm.sportItemId
            if (this.insertForm.matchKindId) data.matchKindId = this.insertForm.matchKindId
            if (this.insertForm.matchEventId) data.matchEventId = this.insertForm.matchEventId
            if (this.insertForm.matchEventItemId) data.matchEventItemId = this.insertForm.matchEventItemId
            if (this.insertForm.multiPlayerMatch) data.multiPlayerMatch = this.insertForm.multiPlayerMatch
            if(this.insertForm.multiPlayerMatch == '个人'){
              if (this.insertForm.playerId) data.playerId = this.insertForm.playerId
            }else if(this.insertForm.multiPlayerMatch == '团体'){
              if (this.insertForm.playerId) data.players = this.insertForm.playerId.join(',')
            }
            if (this.insertForm.genderId) data.genderId = this.insertForm.genderId
            if (this.insertForm.matchGroupTypeId) data.matchGroupTypeId = this.insertForm.matchGroupTypeId
            if (this.insertForm.matchResult) data.matchResult = this.insertForm.matchResult
            if (this.insertForm.delegationId) data.delegationId = this.insertForm.delegationId
            if (this.insertForm.matchRank) data.matchRank = this.insertForm.matchRank
            if (this.insertForm.recordBreakId) data.recordBreakId = this.insertForm.recordBreakId
            if (this.insertForm.protocol) data.protocol = this.insertForm.protocol
            if (this.insertForm.matchAddressId) data.matchAddressId = this.insertForm.matchAddressId
            if (this.insertForm.memo) data.memo = this.insertForm.memo
            data.matchTypeId = 0
            if (this.isInsert) {
              player_match_insert(data).then(res => {
                if (res.code === 200) {
                  this.dataList.unshift(data)
                  this.defaultDataList.push(data)
                  this.init_data(this.defaultDataList)
                  this.page.totalResult+=1
                  this.$refs.XTable.setCurrentRow(this.dataList[0])
                  this.$message.success('保存成功')
                  this.insertSuccess = true
                } else {
                  this.$message.error(res.message)
                }
              })
            } else {
              data.matchId = this.matchId
              player_match_update(data).then(res => {
                if (res.code === 200) {
                  Object.assign(this.dataList[this.currentIndex],res.data)
                  this.defaultDataList.forEach(item=>{
                  	if(res.data.matchId==item.matchId){
                  	  Object.assign(item,res.data)
                  	}
                  })
                  this.init_data(this.defaultDataList)
                  this.$message.success('修改成功')
                  this.insertModal = false
                } else {
                  this.$message.error(res.message)
                }
              })
            }
          } else {
            return false;
          }
        })
      },
      insertEvent() {
        this.isInsert = true
        this.insertModal = true
      },
      sportChange() {
        this.insertForm.sportItemId = ''
        sport_item_by_sportId({
          sportId: this.insertForm.sportId
        }).then(res => {
          if (res.code === 200) {
            this.sportItemData = res.data
          }
        })
      },
      matchEventChange() {
        this.insertForm.matchEventItemId = ''
        match_event_item_by_matchEventId(this.insertForm.matchEventId).then(res => {
          if (res.code === 200) {
            this.matchEventItemData = res.data
          }
        })
      },
      searchMatchEventChange() {
        this.searchForm.matchEventItemId = ''
        match_event_item_by_matchEventId(this.searchForm.matchEventId).then(res => {
          if (res.code === 200) {
            this.matchEventItemData = res.data
          }
        })
      },
      exportData() {
        this.$refs.XTable.exportData({
          filename: this.$store.state.user.org+'运动员'+this.$route.meta.title, type: 'csv',
          data: this.search?this.dataList:this.defaultDataList
        })
      },
      printEvent() {
        let topHtml = '<h2>比赛成绩</h2>'
        this.searchEvent()
        setTimeout(() => {
          this.$refs.XTable.print({
            sheetName: '比赛成绩',
            beforePrintMethod: ({
              content
            }) => {
              return topHtml + content
            }
          })
        }, 1000)
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
          	currentPage: 1,
          	pageSize: this.dataList.length,
          	totalResult: this.dataList.length
          }
          this.search = true
        } else {
          this.dataList = this.defaultDataList
     }
      },
      player_match() {
        this.loading = true
        player_match().then(res => {
          if (res.code === 200 && res.data.length != 0) {
            this.init_data(res.data)
          } else {
            this.defaultDataList = []
          }
        }).then(() => {
          this.findList()
        })
      },
      init_data(data) {
        if(data.length==0) return
        data.forEach(item => {
          if(item.coaches){
            let coachArr = item.coaches.split(',')
            let arr = []
            coachArr.forEach(coach=>{
              arr.push(this.dict_coach[coach])
            })
            item.coachNames = arr.join(',')
          }
          if(item.multiPlayerMatch == '个人'){
            if (item.playerId) item.player = this.dict_player[item.playerId]
          }else if(item.multiPlayerMatch == '团体'){
            if (item.players) {
              let arr = item.players.split(',')
              let playerArr = []
              arr.forEach(playerId=>{
                playerArr.push(this.dict_player[playerId])
              })
              item.player = playerArr.join(',')
            }else{
              item.player = ''
            }
          }else{
            item.player = this.dict_player[item.playerId]
          }
          item.sport = this.dict_sport[item.sportId]
          item.sportItem = this.dict_sportItem[item.sportItemId]
          item.matchDate = this.$moment(item.matchDate).format('YYYY-MM-DD') == 'Invalid date'?'':this.$moment(item.matchDate).format('YYYY-MM-DD')
          item.matchLevel = this.dict_matchLevel[item.matchLevelId]
          item.matchKin = this.dict_matchKin[item.matchKinId]
          item.matchEvent = this.dict_matchEvent[item.matchEventId]
          item.matchEventItem = this.dict_matchEventItem[item.matchEventItemId]
          item.matchGroupType = this.dict_matchGroupType[item.matchGroupTypeId]
          item.delegation = this.dict_delegation[item.delegationId]
          item.matchAddress = this.dict_matchAddress[item.matchAddressId]
          item.recordBreak = this.dict_recordBreak[item.recordBreakId]
          item.matchRank = item.matchRank==0?'':item.matchRank
          item.createUser = this.dict_userId2empName[item.createUserId]
          if (item.checkUserId&&item.checkUserId!='0') {
            item.checkUser = this.dict_userId2empName[item.checkUserId]
          } else {
            item.checkUser = '未审核'
          }
        })
        this.searchProps = Object.keys(data[0])
        this.defaultDataList = data
      },
      init_dict() {
        return new Promise((resolve, reject) => {
          coachByOrgIgnoreRole().then(res => {
            this.dict_coach = res
          })
          sport_by_org().then(res => {
            this.dict_sport = res
          })
          sport_item().then(res => {
            this.dict_sportItem = res
          })
          match_event().then(res => {
            this.dict_matchEvent = res
          })
          match_event_item().then(res => {
            this.dict_matchEventItem = res
          })
          getDelegation().then(res => {
            this.dict_delegation = res
          })
          record_break().then(res => {
            this.dict_recordBreak = res
          })
          match_level().then(res => {
            this.dict_matchLevel = res
          })
          match_group_type().then(res => {
            this.dict_matchGroupType = res
          })
          match_kind().then(res => {
            this.dict_matchKin = res
          })
          match_address().then(res => {
            this.dict_matchAddress = res
          })
          userId2EmpName().then(res => {
            this.dict_userId2empName = res
          })
          currentRolePlayer(true).then(res => {
            res.forEach(item=>{
              this.dict_playerId_genderId[item.playerId] = item.genderId
              this.dict_player[item.playerId] = item.name
            })
            resolve()
          })
        })
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
      	if(!this.search){
          this.page.currentPage = 1
      	  this.page.pageSize = this.defaultDataList.length
      	  this.findList()
      	}else{
      	  this.page.pageSize = this.dataList.length
      	}
      },
      findList() {
        this.loading = true
        setTimeout(() => {
          if(this.insertSuccess){
            this.page.totalResult = this.defaultDataList.length
            this.page.currentPage = Math.ceil(this.page.totalResult/this.page.pageSize)
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
            this.$refs.XTable.setCurrentRow(this.dataList[this.dataList.length-1])
            this.insertSuccess = false
          }else{
            this.page.totalResult = this.defaultDataList.length
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
          }
          this.loading = false
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>

</style>
